<?php
/**
*
* 
*
*/
error_reporting(E_ERROR || E_PARSE);
set_magic_quotes_runtime(0);
function_exists('date_default_timezone_set') && date_default_timezone_set('Etc/GMT+8');
$t_array = explode(' ',microtime());
$P_S_T	 = $t_array[0] + $t_array[1];
$timestamp = time();

define('D_P',__FILE__ ?	getdirname(__FILE__).'/' :	'./');
define('R_P',D_P);

unset($_ENV,$HTTP_ENV_VARS,$HTTP_POST_VARS,$HTTP_GET_VARS,$HTTP_POST_FILES,$HTTP_COOKIE_VARS);
if(!get_magic_quotes_gpc()){
	Add_S($_POST);
	Add_S($_GET);
	Add_S($_COOKIE);
}
Add_S($_FILES);

foreach($_POST as $_key=>$_value){
	!ereg("^\_",$_key) && !isset($$_key) && $$_key=$_POST[$_key];
}

foreach($_GET as $_key=>$_value){
	!ereg("^\_",$_key) && !isset($$_key) && $$_key=$_GET[$_key];
}

if($_SERVER['HTTP_X_FORWARDED_FOR']){
	$onlineip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}elseif($_SERVER['HTTP_CLIENT_IP']){
	$onlineip = $_SERVER['HTTP_CLIENT_IP'];
}else{
	$onlineip = $_SERVER['REMOTE_ADDR'];
}
$onlineip = preg_match("/^[\d]([\d\.]){5,13}[\d]$/", $onlineip) ? $onlineip : 'unknown';
!$_SERVER['PHP_SELF'] && $_SERVER['PHP_SELF']=$_SERVER['SCRIPT_NAME'];
$REQUEST_URI  = $_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];

require_once(D_P.'data/cache/config.php');

/* 内网IP判断 */
/*
if (!empty($very['ip']) && $_SERVER['SERVER_ADDR'] != $very['ip']) //当前访问的IP等于内网IP
{
if (!empty($very['lanurl']) && !empty($very['lanip']))
{
$lanIp = explode("\r\n", $very['lanip']);
foreach ($lanIp as $lanArea)
{
if (strpos($onlineip, $lanArea) !== false) {
$jumpurl = $very['lanurl'];
if (SCR == 'nbc_index') {
header("Location:$jumpurl/nbc_index.php?userid=" . $nbcId . "&userpwd=" . $nbcPwd);
} else {
header("Location:$jumpurl");
}
exit;
}
}
}
}
*/


/* 构建一个URL */
$very['url'] = getUrlPath();
empty($very['contentName']) && $very['contentName'] = '专题';
$very['brower'] = IsCompatible(); //浏览器版本
$very['logo'] = !empty($very['logo']) ? 'data/logo.' . $very['logo'] : 'images/logo.png';
require_once(D_P.'data/sql_config.php');
require_once(R_P.'require/class_db.php');
//include_once(D_P.'data/cache/nav.php');
$queryNum = 0;
$db = new DB($dbhost,$dbuser,$dbpw,$dbname,$charset,$pconnect);

$_OUTPUT = '';
$wind_spend = '';
$wind_version = "2.0";
$wind_repair = readover(R_P . 'version.dat');
$cssname = empty($very['tpl']) ? 'default' : $very['tpl'];
/*
$user_tplpath = 'template/user'; //用户模板路径
$default_tplpath = 'template/default'; //系统模板路径
*/

if($very['rewrite_dir'] && $very['rewrite_ext'])
{
	$self_array = explode('-',$very['rewrite_ext'] ? substr($_SERVER['QUERY_STRING'],0,strpos($_SERVER['QUERY_STRING'],$very['rewrite_ext'])) : $_SERVER['QUERY_STRING']);
	$s_count=count($self_array);
	for($i=0;$i<$s_count;$i++)
	{
		$_key	= $self_array[$i];
		$_value	= $self_array[++$i];
		!ereg("^\_",$_key) && !isset($$_key) && $$_key = addslashes(rawurldecode($_value));
	}
}


############################################################################################

//主要函数库

function start($charset=''){
	global $very;
	!$charset && $charset='utf-8';
	$very['obstart'] == 1 && function_exists('ob_gzhandler') ? ob_start('ob_gzhandler') : ob_start();
	$charset && @header("Content-Type: text/html; charset=$charset");
}

/**
 * 写Cookie
 *
 * @param string $ck_Var Cookie变量名
 * @param string $ck_Value 值
 * @param integer $ck_Time 保存时间
 */
function Cookie($ck_Var,$ck_Value,$ck_Time=null, $ck_Httponly=true){
	global $timestamp;

	$db_ckpath = '';
	$db_ckdomain = '';

	if (!$_SERVER['REQUEST_URI'] || ($https = @parse_url($_SERVER['REQUEST_URI']))===false) {
		$https = array();
	}
	if ((empty($https['scheme']) && ($_SERVER['HTTP_SCHEME']=='https' || $_SERVER['HTTPS'] && strtolower($_SERVER['HTTPS'])!='off')) || $https['scheme']=='https') {
		$ck_Secure = true;
	} else {
		$ck_Secure = false;
	}

	!$db_ckpath && $db_ckpath = '';
	if ($ck_Time=='F') {
		$ck_Time = $timestamp+31536000;
	} elseif ($ck_Value=='' && $ck_Time==0) {
		return setcookie($ck_Var,'',$timestamp-31536000,$db_ckpath,$db_ckdomain,$ck_Secure);
	}
	if (PHP_VERSION>='5.2.0') {
		return setcookie($ck_Var,$ck_Value,$ck_Time,$db_ckpath,$db_ckdomain);
	} else {
		return setcookie($ck_Var,$ck_Value,$ck_Time,$db_ckpath.($ck_Httponly ? '; HttpOnly' : ''),$db_ckdomain,$ck_Secure);
	}
}

function PwStrtoTime($time){
	global $very;
	return function_exists('date_default_timezone_set') ? strtotime($time) - $very['timedf']*3600 : strtotime($time);
}

/**
 * 读Cookie
 *
 * @param string $Var
 * @return mixed
 */
function GetCookie($Var){
	return $_COOKIE[$Var];
	//return $_COOKIE[CookiePre().'_'.$Var];
}

function CookiePre(){
	global $very;
	return substr(md5($very['hash']),0,5);
}

function Char_cv($msg){
	$msg = str_replace('&amp;','&',$msg);
	$msg = str_replace('&nbsp;',' ',$msg);
	$msg = str_replace('"','&quot;',$msg);
	$msg = str_replace("'",'&#39;',$msg);
	$msg = str_replace("<","&lt;",$msg);
	$msg = str_replace(">","&gt;",$msg);
	$msg = str_replace("\t","   &nbsp;  &nbsp;",$msg);
	$msg = str_replace("\r","",$msg);
	$msg = str_replace("   "," &nbsp; ",$msg);
	return $msg;
}

function Add_S(&$array){
	foreach($array as $key=>$value){
		if(!is_array($value)){
			$array[$key]=addslashes($value);
		}else{
			Add_S($array[$key]);
		}
	}
}

function get_date($timestamp,$timeformat=''){
	global $very,$_datefm,$_timedf;
	$date_show=$timeformat ? $timeformat : ($_datefm ? $_datefm : $very['datefm']);
	if($_timedf){
		$offset = $_timedf=='111' ? 0 : $_timedf;
	}else{
		$offset = $very['timedf']=='111' ? 0 : $very['timedf'];
	}
	return gmdate($date_show,$timestamp+$offset*3600);
}

/**
 * 截取字符串,多编码
 *
 * @param string $content	原字符串
 * @param string $length	截取长度
 * @param string $num		0=字节  1=个数
 * @param string $add		结尾添加 '..'
 * @param string $code		编码 utf-8或其他
 * @return string
 */
function substrs($content,$length,$num=0,$add=1,$code=''){
	global $very;
	$code = $code ? $code : strtoupper($very['lang']);
	if($length && strlen($content)>$length){
		$retstr='';
		if($code == 'UTF-8'){
			$retstr = utf8_trim($content,$length,$num);
		}else{
			for($i = 0; $i < $length; $i++) {
				if(ord($content[$i]) > 127){
					if($num){
						$retstr .=$content[$i].$content[$i+1];
						$i++;
						$length++;
					}elseif(($i+1<$length)){
						$retstr .=$content[$i].$content[$i+1];
						$i++;
					}
				}else{
					$retstr .=$content[$i];
				}
			}
		}
		return $retstr.($add ? '..' : '');
	}
	return $content;
}

function utf8_trim($string,$length,$num) {
	if($length && strlen($string)>$length){
		if($num){
			$pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
			preg_match_all($pa, $string, $t_string);
			return join('', array_slice($t_string[0], 0, $length));
		}else{
			$hex = '';
			$str = substr($string,0,$length);
			for($i=$length-1;$i>=0;$i--){
				$ch   = ord($str[$i]);
				$hex .= ' '.$ch;
				if(($ch & 128)==0)	return substr($str,0,$i);
				if(($ch & 192)==192)return substr($str,0,$i);
			}
			return($str.$hex);
		}
	}
	return $string;
}

/**
 * 读取文件内容
 *
 * @copyright PHPWind
 * @param string $filename
 * @param string $method
 * @return string
 */
function readover($filename,$method="rb"){
	strpos($filename,'..')!==false && exit('Forbidden');
	if($handle=@fopen($filename,$method)){
		flock($handle,LOCK_SH);
		$filedata=fread($handle,filesize($filename));
		fclose($handle);
	}
	return $filedata;
}

/**
 * 将指定内容写入文件
 *
 * @copyright PHPWind
 * @param string $filename 文件名
 * @param string $data 要写入的数据
 * @param string $method 操作方法
 * @param boolean $iflock 是否锁定
 */
function writeover($filename,$data,$method="rb+",$iflock=1,$check=1,$chmod=1){
	$check && strpos($filename,'..')!==false && exit('Forbidden');
	touch($filename);
	$handle=fopen($filename,$method);
	$iflock && flock($handle,LOCK_EX);
	if(@fwrite($handle,$data)=== FALSE){
		fclose($handle);
		return false;
	}
	if($method=="rb+") ftruncate($handle,strlen($data));
	fclose($handle);
	$chmod && @chmod($filename,0777);
	return true;
}

/**
 * 模板包含程序
 *
 * @param 模板名 $template
 * @param 后缀 $EXT
 * @return 完整的真实路径
 */
function PrintEot($template, $EXT="htm")
{
	global $tplpath, $very;
	if(!$template) $template=N;

	$path=R_P."template/$tplpath/$template.$EXT";
	!file_exists($path) && $path=R_P."template/user/$template.$EXT";
	return $path;
}

function getdirname($path){
	if(strpos($path,'\\')!==false){
		return substr($path,0,strrpos($path,'\\'));
	}elseif(strpos($path,'/')!==false){
		return substr($path,0,strrpos($path,'/'));
	}else{
		return '/';
	}
}

function GdConfirm($code){
	Cookie('cknum','',0);
	if(!$code || !SafeCheck(explode("\t",StrCode(GetCookie('cknum'),'DECODE')),$code,'cknum',1800)){
		if(function_exists('adminmsg')){
			Showmsg('ckerror');
		}else{
			echo "ckerror";
			exit();
		}
	}
}

function SafeCheck($CK,$PwdCode,$var='AdminUser',$expire=1800)
{
	global $timestamp;
	$t	= $timestamp - $CK[0];
	if($t > $expire || $CK[2] != md5($PwdCode.$CK[0])){
		Cookie($var,'',0);
		return false;
	}else{
		$CK[0] = $timestamp;
		$CK[2] = md5($PwdCode.$timestamp);
		$Value = implode("\t",$CK);
		$$var  = StrCode($Value);
		Cookie($var,StrCode($Value));
		return true;
	}
}

function StrCode($string,$action='ENCODE'){
	global $very;
	$key	= substr(md5($_SERVER["HTTP_USER_AGENT"].$very['hash']),8,18);
	$string	= $action == 'ENCODE' ? $string : base64_decode($string);
	$len	= strlen($key);
	$code	= '';
	for($i=0; $i<strlen($string); $i++){
		$k		= $i % $len;
		$code  .= $string[$i] ^ $key[$k];
	}
	$code = $action == 'DECODE' ? $code : base64_encode($code);
	return $code;
}

function randstr($lenth){
	mt_srand((double)microtime() * 1000000);
	for($i=0;$i<$lenth;$i++){
		$randval.= mt_rand(0,9);
	}
	$randval=substr(md5($randval),mt_rand(0,32-$lenth),$lenth);
	return $randval;
}

function num_rand($lenth){
	mt_srand((double)microtime() * 1000000);
	for($i=0;$i<$lenth;$i++){
		$randval.= mt_rand(0,9);
	}
	return $randval;
}

/**
 * 返回语言包文件
 *
 * @param string $filename
 * @return string
 */
function GetLang($filename){
	global $very;
	empty($very['lang']) && $very['lang']='gbk';
	return R_P."lang/$very[lang]/$filename.php";
}

/**
 * 得到分页内容
 *
 * @param integer $count 数量合计
 * @param integer $page 当前页
 * @param integer $numofpage 合计页
 * @param string $url 分页url
 * @param integer $max
 * @return string
 */
function numofpage($count,$page,$numofpage,$url,$max=0)
{
	$total = $numofpage;
	if ($page < 1) $page = 1;
	$max && $numofpage > $max && $numofpage=$max;
	if ($numofpage <= 1 || !is_numeric($page))
	{
		return '';
	}
	else
	{
		$pages="<div class=\"pages\"><a href=\"{$url}page=1\" style=\"font-weight:bold\">&laquo;</a>";
		$flag=0;
		for($i=$page-3;$i<=$page-1;$i++){
			if($i<1) continue;
			$pages.="<a href=\"{$url}page=$i\">$i</a>";
		}
		$pages.="<b> $page </b>";
		if($page<$numofpage){
			for($i=$page+1;$i<=$numofpage;$i++){
				$pages.="<a href=\"{$url}page=$i\">$i</a>";
				$flag++;
				if($flag==4) break;
			}
		}
		$pages.="<input type=\"text\" size=\"3\" onkeydown=\"javascript: if(event.keyCode==13){ location='{$url}page='+this.value;return false;}\"><a href=\"{$url}page=$numofpage\" style=\"font-weight:bold\">&raquo;</a> Pages: ( $page/$total total )</div>";
		return $pages;
	}
}

/**
 * 抛出一个致命的程序错误
 *
 * @param string $msg
 */
function throwError($msg){
	ob_end_clean();
	header("Content-Type: text/html; charset=utf-8");
	extract($GLOBALS, EXTR_SKIP);
	require GetLang('error');
	$lang[$msg] && $msg=$lang[$msg];
	$errmsg="<div style='font-size:12px;font-family:verdana;line-height:180%;color:#000;border:dashed 1px #ccc;padding:10px;margin:20px;'>";
	$errmsg.="<span style='color:red;font-weight:bold'>Error: </span>";
	$errmsg.=$msg;
	$errmsg.="</div>";
	die($errmsg);
}

/*function __autoload($class_name) { //PHP5
$class_name = strtolower($class_name);
require_once R_P.'require/class_'.$class_name.'.php';
}*/

/**
 * 结束ob输出，并把缓存输出到浏览器或者赋值给指定变量以生成静态
 *
 */
function footer(){
	global $very,$_OUTPUT,$cid,$page;
	$output = str_replace(array('<!--<!---->','<!---->'),array('',''),ob_get_contents());
	if($very['rewrite']){
		$output = preg_replace(
		"/\<a(\s*[^\>]+\s*)href\=([\"|\']?)([^\"\'>\s]+\.php\?[^\"\'>\s]+)([\"|\']?)/ies",
		"Htm_cv('\\3','<a\\1href=\"')",
		$output
		);
	}
	ob_end_clean();
	if(class_exists('Action') || function_exists('adminmsg')){
		//如果是后台传入,则为生成静态动作
		$_OUTPUT = $output;
	}else{
		$very['obstart'] == 1 && function_exists('ob_gzhandler') ? ob_start('ob_gzhandler') : ob_start();
		$cid = intval($cid);
		$page = $page ? intval($page) : 1;
		SCR == 'list' && $output .= "\n<script src='update.php?type=list&cid=".$cid."&page=".$page."'></script>";
		echo $output;
		flush;
		exit;
	}
}

/**
 * 页面伪静态化
 *
 * @param string $url
 * @param string $tag
 * @return string
 */
function Htm_cv($url,$tag){
	global $very;
	if(ereg("^http|ftp|telnet|mms|rtsp|admin.php|rss.php",$url)===false){
		if(strpos($url,'#')!==false){
			$add = substr($url,strpos($url,'#'));
		}
		$url = str_replace(
		array('.php?','=','&',$add),
		array($very['rewrite_dir'],'-','-',''),
		htmlchars_decode($url)
		).$very['rewrite_ext'].$add;
	}
	return $tag.$url.'"';
}

/**
 * 返回一个模板文件的编译路径
 *
 * @param string $tplname
 * @return string
 */
function Template($tplname = ''){
	global $cid,$user_tplpath,$default_tplpath,$catedb;
	if(!$catedb) require_once(D_P.'data/cache/cate.php');
	require_once(R_P.'require/template.php');
	return Tpl($tplname);
}



/**
 * 根据原图返回一个缩略图路径
 *
 * @param string $sourceImg 原图路径
 * @param integer $width 缩略宽度
 * @param integer $height 缩略高速
 * @param integer $quality 缩略质量
 * @return string
 */
function miniImg($sourceImg,$width,$height,$quality=85)
{
	global $very,$attach;
	if ($very['skipgif']) { //忽略对Gif图片的处理
		if(strtolower(end(explode('.',$sourceImg))) == 'gif') return $sourceImg;
	}
	require_once(R_P.'require/class_attach.php'); //需要对附件进行处理，调用附件处理类
	if(!is_object($attach)){ //倘若类没有实例化，则new之
		$attach = new Attach();
	}
	$attach->picheight = $height;
	$attach->picwidth = $width;
	list($sourceImg,$targetImg,$SmallImg) = $attach->getAttachPath($sourceImg);
	if(!filesize($targetImg)){
		$attach->resize_image($sourceImg,$targetImg,$width,$height,$quality);
	}
	return $SmallImg;
}

/**
 * 检验访问方式是否合法，是否应该通过静态来访问
 *
 */
function checkRefer(){
	global $catedb,$very,$cid,$tid,$db;
	if(function_exists('adminmsg')) return ; //说明是后台浏览
	$tid = (int)$tid;
	$cid = (int)$cid;
	if(SCR=='list'){
		!$cid && throwError('nocid');
		//!$catedb[$cid]['type'] && throwError('notpubcate');
		if($catedb[$cid]['listpub'] && $catedb[$cid]['listurl']){
			if(!function_exists('adminmsg')){
				$jumpurl = $catedb[$cid]['listurl'];
				echo "<script language='javascript'>\n";
				echo "window.location='$jumpurl';\n";
				echo "</script>";
				exit();
			}
		}
		return ;
	}elseif (SCR=='view'){
		!$cid && throwError('nocid');
		//!$catedb[$cid]['type'] && throwError('notpubcate');
		if($catedb[$cid]['htmlpub'] && !function_exists('adminmsg')){
			$mid = $catedb[$cid]['mid'];
			if ($mid<=0) return;
			//if($mid == -2){return;}
			$rs = $db->get_one("SELECT url FROM cms_contentindex WHERE tid='$tid' AND cid='$cid' AND ifpub=1");
			if($rs){
				$jumpurl = $very['htmdir'].'/'.$rs['url'];
				echo "<script language='javascript'>\n";
				echo "window.location='$jumpurl';\n";
				echo "</script>";
				exit();
			}else{
				throwError('data_error');
			}
		}
		return ;
	}elseif (SCR=='index'){
		if(/*$very['htmlindex'] && */!function_exists('adminmsg')){
			if(!file_exists(R_P.'index.html')){
				exit("首页尚未生成，请到后台更新首页");
			}else{
				ObHeader('index.html'); //倘若不是发布动作，转向到静态页
			}
		}
	}
}

function ObHeader($URL){
	global $very;
	if($very['rewrite'] && strtolower(substr($URL,0,4))!='http'){
		$URL="$very[url]/$URL";
	}
	if($very['obstart']){
		header("Location: $URL");exit;
	}else{
		ob_start();
		echo "<meta http-equiv='refresh' content='0;url=$URL'>";
		exit;
	}
}

/**
 * 根据PW特有格式返回数组
 *
 * @param string $filename
 * @return array
 */
function openfile($filename){
	$filedata=readover($filename);
	$filedata=str_replace("\n","\n<:wind:>",$filedata);
	$filedb=explode("<:wind:>",$filedata);
	$count=count($filedb);
	if($filedb[$count-1]==''||$filedb[$count-1]=="\r"){unset($filedb[$count-1]);}
	if(empty($filedb)){$filedb[0]="";}
	return $filedb;
}

/**
 * 生成一个随机字符串
 *
 * @param integer $num
 * @return string
 */
function randomStr($num){
	$word = 'abcdefghijklmnopqrstuvwxyz0123456789';
	$len = strlen($word);
	$len = $len-2;
	$str = '';
	for ($x=0;$x<$num;$x++){
		$i = rand(0,$len);
		$theword = substr($word,$i,1);
		$str .= $theword;
	}
	return $str;
}

/**
 * 生成随机字符串
 *
 * @param integer $len
 * @return string
 */
function generateStr($len){
	global $very;
	mt_srand((double)microtime() * 1000000);
	$keychars = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWYXZ";
	$maxlen = strlen($keychars)-1;
	$str = '';
	for ($i=0;$i<$len;$i++){
		$str .= $keychars[mt_rand(0,$maxlen)];
	}
	return substr(md5($str.time().$_SERVER["HTTP_USER_AGENT"].$very['hash']),mt_rand(0,32-$len),$len);
}
/**
 * 判断浏览器类型
 *
 * @param
 * @return string 
 *   Array['Type']		浏览器类型: MSIE  Gecko  Opera  Safari
 *   Array['Version']	浏览器版本:
 */
function IsBrowser(){
	global $HTTP_USER_AGENT ;

	if ( isset( $HTTP_USER_AGENT ) ){
		$sAgent = $HTTP_USER_AGENT ;
	}else{
		$sAgent = $_SERVER['HTTP_USER_AGENT'] ;
	}
	$result = array();
	if ( strpos($sAgent, 'MSIE') !== false && strpos($sAgent, 'mac') === false && strpos($sAgent, 'Opera') === false ){
		$result['Type'] = 'MSIE';
		$result['Version'] = (float)substr($sAgent, strpos($sAgent, 'MSIE') + 5, 3);
	}else if ( strpos($sAgent, 'Gecko/') !== false ){
		$result['Type'] = 'Gecko';
		$result['Version'] = (int)substr($sAgent, strpos($sAgent, 'Gecko/') + 6, 8);
	}else if (strpos($sAgent,'Opera/') !== false){
		$result['Type'] = 'Opera';
		$result['Version'] = (int)substr($sAgent,strpos($sAgent,'Opera/')+6,5);
	}else if (strpos($sAgent,'Safari/') !== false){
		$result['Type'] = 'Safari';
		$result['Version'] = (int)substr($sAgent,strpos($sAgent,'Safari/')+7,8);
	}else{
		return false;
	}
	return $result;
}
/**
 * html标签匹配
 *
 * @return string
 */
function htmlbalance($str){
	preg_match_all ("/<([\w]+)[^>]*>.*/",$str, $htmlbegin);
	preg_match_all ("/<([\/][\w]+)[^>]*>.*/",$str, $htmlend);
	$sinhtml=array("br","BR","input","INPUT","hr","HR","img","IMG");
	$htmlbegin[1]=array_diff($htmlbegin[1],$sinhtml);
	if(count($htmlbegin[1])==count($htmlend[1])){
		return $str;
	}else{
		$htmlbegin=array_change_key_case(array_count_values($htmlbegin[1]));
		$htmlend=array_change_key_case(array_count_values($htmlend[1]));
		foreach($htmlbegin as $key=>$val){
			$keyend="/".$key;
			@$htmlend[$keyend]=$htmlend[$keyend]?$htmlend[$keyend]:0;
			$htmlcount=$val-$htmlend[$keyend];
			if($htmlcount){
				for($i=0;$i<$htmlcount;$i++){
					$str.="<".$keyend.">";
				}
			}
		}
		return $str;
	}
}

function htmlchars_decode($str){
	$encode = array('&amp;','&quot;','&#039;','&lt;','&gt;');
	$decode = array('&','"','\'','<','>');
	$str = str_replace($encode,$decode,$str);
	return $str;
}

function getSmallPic($path, $type)
{
	$ext = end(explode('.', $path));
	$len = strlen($ext);
	$len++;
	return substr($path, 0, -$len) . '_s' . $type . '.' . $ext;
}

/**
 * 返回用户的登录状态
 *
 * @return mixed
 */
function checkLogin()
{
	if (defined('ADMIN')) return null;
	global $db;
	list($username, $password) = explode("\t", GetCookie('login'));
	if(empty($username) || empty($password)) return null;
	$rs = $db->get_one("SELECT uid,username,groupid,ifadmin FROM cms_user WHERE username='$username' AND password='$password'");
	return $rs;
}

/**
 * 弹出一个JS提示错误
 *
 */
function showAlert($msg, $jumpurl = '')
{
	ob_end_clean();
	start();
	echo '<script language="javascript">';
	echo 'alert("' . $msg . '");';
	if (is_null($jumpurl))
	{
		//nothing
	}
	elseif (empty($jumpurl))
	{
		echo 'window.history.go(-1);';
	}
	else
	{
		echo 'window.location="' . $jumpurl . '";';
	}
	echo '</script>';
	exit;
}

/**
 * 获取值
 *
 * @param string $key
 * @return mixed
 */
function getVal($key)
{
	if (!isset($_GET[$key]) && !isset($_POST[$key]))
	{
		return null;
	}
	return isset($_GET[$key]) ? $_GET[$key] : $_POST[$key];
}

function ifcheck($var,$out)
{
	global ${$out.'_Y'},${$out.'_N'},$checks;
	if($var){
		${$out.'_Y'}="CHECKED";
		$checks[$out.'_Y']="CHECKED";
	}else{
		${$out.'_N'}="CHECKED";
		$checks[$out.'_N']="CHECKED";
	}
}

function getUrlPath()
{
	$domain = 'http://' . $_SERVER['HTTP_HOST'];
	$s = $_SERVER['REQUEST_URI'];
	$pathInfo = explode("/", $_SERVER['REQUEST_URI']);
	foreach ($pathInfo as $p)
	{
		if (!empty($p) && strpos($p, '.') === false)
		{
			$domain .= "/$p";
		}
	}
	if (strrpos($domain, "/") === strlen($domain) - 1) {
		$domain = substr($domain, 0, -1);
	}
	return $domain;
}

/**
 * 返回浏览器版本
 *
 * @return unknown
 */
function IsCompatible()
{

	$sAgent = $_SERVER['HTTP_USER_AGENT'] ;

	if ( strpos($sAgent, 'MSIE') !== false && strpos($sAgent, 'mac') === false && strpos($sAgent, 'Opera') === false ){
		$iVersion = (float)substr($sAgent, strpos($sAgent, 'MSIE') + 5, 3) ;
		return ($iVersion >= 7) ;
	}else if ( strpos($sAgent, 'Gecko/') !== false ){
		$iVersion = (int)substr($sAgent, strpos($sAgent, 'Gecko/') + 6, 8) ;
		return ($iVersion >= 20030210) ;
	}else if (strpos($sAgent,'Opera')!==false){
		$iVersion = (int)substr($sAgent,strpos($sAgent,'Opera/')+6,4);
		return ($iVersion >= 9.00);
	}else if (strpos($sAgent,'Safari/') !== false){
		$iVersion = (int)substr($sAgent,strpos($sAgent,'Safari/')+7,3);
		return ($iVersion >= 312);
	}else{
		return false ;
	}
}

/*
admin Functions
*/
function Showmsg($msg){
	if (!function_exists('adminmsg'))
	{
		showAlert($msg);
	}
	extract($GLOBALS, EXTR_SKIP);
	require PrintEot('header');
	require GetLang('cpmsg');
	$lang[$msg] && $msg=$lang[$msg];
	$errmsg="<div style='font-size:12px;font-family:verdana;line-height:180%;color:#666;border:dashed 1px #ccc;padding:1px;margin:20px;'>";
	$errmsg.="<div style=\"background: #eeedea;padding-left:10px;font-weight:bold;height:25px;\">$lang[prompt]</div>";
	$errmsg.="<div style='padding:20px;font-size:14px;'><img src='images/admin/bg_face.gif' align='absmiddle' hspace=20 >$msg</div>";
	$errmsg.="<div style=\"text-align:center;height:30px;\"><input class=btn type=button onclick='window.history.go(-1)' value=' $lang[back] ' /></div>";
	$errmsg.="</div>";
	die($errmsg);
}
?>